#!/usr/bin/env python
#

import cgi
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.ext import webapp



class RemoteObject ( db.Model ) :
  name = db.StringProperty()
  data = db.BlobProperty()



class GetObject ( webapp.RequestHandler ) :
  def get ( self ) :
    objName = self.request.path_info.split( "/" )[-1]
    
    self.response.headers['Content-Type'] = 'application/zip'

    query = RemoteObject.gql( "WHERE name = :1", objName )

    robj = query.get()

    if robj != None :
      self.response.out.write( robj.data )
    else :
      self.error( 404 )



class StoreObject ( webapp.RequestHandler ) :
  def put ( self ) :
    objName = self.request.path_info.split( "/" )[-1]

    robj = RemoteObject( key_name = "wd_" + objName )

    robj.name = objName
    robj.data = self.request.body
    robj.put()

    self.response.out.write( '<html><body>Stored: \'%s\'</body></html>' % robj.name );



class RemoveObject ( webapp.RequestHandler ) :
  def get ( self ) :
    objName = self.request.path_info.split( "/" )[-1]

    query = RemoteObject.gql( "WHERE name = :1", objName )

    for robj in query :
      robj.delete()

    self.response.out.write( '<html><body>Removed: \'%s\'</body></html>' % robj.name );



application = webapp.WSGIApplication([
  ( '/get/.*', GetObject ),
  ( '/store/.*', StoreObject ),
  ( '/remove/.*', RemoveObject )
], debug=True)


def main():
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
